<template>
  <a-modal
    v-model:open="visible"
    title="关联工单"
    @cancel="handleCancel"
    :footer="null"
    destroyOnClose
    :width="500"
    centered
  >
    <div
      v-if="!relateWorkOrderCode && !showAddExist && !showAddNew"
      class="content"
    >
      <div class="tip">
        暂未关联工单，可点击添加已发起的工单，或直接发起新的工单
      </div>
      <div class="footer">
        <a-button type="primary" @click="handleAddExist"
          >添加已发起工单</a-button
        >
        <a-button type="primary" @click="handleAddNew" class="yellowBtn"
          >发起新工单</a-button
        >
      </div>
    </div>

    <!-- 添加已发起工单 -->
    <div v-if="showAddExist">
      <a-form :model="form" layout="inline" :rules="rules" ref="formRef">
        <a-form-item label="关联工单编号" name="relateWorkOrderCode">
          <!--   <a-input
            v-model:value="form.relateWorkOrderCode"
            placeholder="请输入"
            class="formSelect"
          /> -->
          <a-select
            v-model:value="form.relateWorkOrderCode"
            class="formSelect"
            placeholder="请选择"
            show-search
            optionFilterProp="label"
            allow-clear
          >
            <a-select-option
              v-for="item in workListType"
              :key="item.serialCode"
              :value="item.serialCode"
              :label="item.serialCode"
            >
              {{ item.serialCode }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
      <div class="footer">
        <a-button @click="handleCancel">关闭</a-button>
        <a-button type="primary" @click="handleSave">保存</a-button>
      </div>
    </div>

    <!-- 发起新工单 -->
    <div v-if="showAddNew">
      <a-form
        :model="form"
        :rules="rules"
        ref="formRef"
        :labelCol="{
          style: {
            width: '110px',
          },
        }"
      >
        <a-form-item label="工单优先级" name="exceptionPriority">
          <a-select
            v-model:value="form.exceptionPriority"
            class="formInput"
            placeholder="请选择"
            allow-clear
            show-search
            optionFilterProp="label"
          >
            <a-select-option
              v-for="item in WORK_ORDER_PRIORITY_LIST"
              :value="item.value"
              :key="item.value"
              :label="item.label"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="上传附件">
          <a-upload
            v-model:file-list="fileList"
            name="file"
            list-type="picture-card"
            class="addEquipUpload"
            :action="uploadUrl"
            :headers="headers"
            :multiple="true"
            method="post"
            :preview-file="previewFile"
            :before-upload="beforeUpload"
            @change="handleUploadChange"
            @remove="handleRemove"
          >
            <div>
              <loading-outlined v-if="loading"></loading-outlined>
              <plus-outlined v-else></plus-outlined>
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
        </a-form-item>
      </a-form>
      <div class="footer">
        <a-button @click="handleCancel">关闭</a-button>
        <a-button type="primary" @click="handleSubmit" :loading="loading"
          >发起工单</a-button
        >
      </div>
    </div>

    <!-- 查看关联工单 -->
    <div v-if="relateWorkOrderCode && !isEdit">
      <div class="work-order-info">
        <span>关联工单编号：{{ relateWorkOrderCode }}</span>
      </div>
      <div class="footer">
        <a-button @click="handleCancel">关闭</a-button>
        <a-button type="primary" @click="handleEdit">修改</a-button>
      </div>
    </div>

    <!-- 修改关联工单 -->
    <div v-if="isEdit">
      <a-form :model="form" layout="inline" :rules="rules" ref="formRef">
        <a-form-item label="关联工单编号" name="relateWorkOrderCode">
          <a-select
            v-model:value="form.relateWorkOrderCode"
            class="formSelect"
            placeholder="请选择"
            show-search
            optionFilterProp="label"
            allow-clear
          >
            <a-select-option
              v-for="item in workListType"
              :key="item.serialCode"
              :value="item.serialCode"
              :label="item.serialCode"
            >
              {{ item.serialCode }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
      <div class="footer">
        <a-button @click="handleCancel">关闭</a-button>
        <a-button type="primary" @click="handleSave">保存</a-button>
      </div>
    </div>
  </a-modal>
</template>

<script setup>

import { PlusOutlined } from "@ant-design/icons-vue"
import {
  WORK_ORDER_PRIORITY_LIST,
  WORK_ORDER_TYPE,
} from "@/constants/workOrder"
import storage from "@/utils/storage"
const $api = inject("$api")
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  relateWorkOrderCode: {
    type: String,
    default: "",
  },
  rowData: {
    type: Object,
    default: () => {},
  },
})
const rules = {
  relateWorkOrderCode: [
    { required: true, message: "请输入关联工单编号", trigger: "change" },
  ],
  exceptionPriority: [
    { required: true, message: "请选择工单优先级", trigger: "change" },
  ],
}
const visible = ref(false)
const form = ref({
  relateWorkOrderCode: null,
  id: null,
  relateType: 2,
  exceptionPriority: null,
  stationId: null,
  exceptionDesc: null,
  exceptionOperateSuggest: null,
  attachFileIds: null,
  faultConvertWorkOrder: true,
  type: WORK_ORDER_TYPE.ERROR,
})
watch(
  () => props.visible,
  (val) => {
    visible.value = val
    handleSearchWorkOder()
    if (val && props.rowData) {
      form.value = {
        id: props.rowData.id,
        relateType: props.rowData?.relateType || 1,
        relateWorkOrderCode: props.rowData?.relateWorkOrderCode || "",
        stationId: props.rowData?.stationId || "",
        exceptionDesc: props.rowData?.faultDesc || "",
        exceptionOperateSuggest: props.rowData?.faultDealDesc || "",
        attachFileIds: undefined,
        faultConvertWorkOrder: true,
        faultConvertWorkOrder: true,
        type: WORK_ORDER_TYPE.ERROR,
      }
    }
  }
)
const emit = defineEmits(["update:visible", "save", "refresh"])

const showAddExist = ref(false)
const showAddNew = ref(false)
const isEdit = ref(false)

const handleAddExist = () => {
  showAddExist.value = true
  showAddNew.value = false
  form.value.relateWorkOrderCode = null
}

const handleAddNew = () => {
  showAddNew.value = true
  showAddExist.value = false
}

const handleEdit = () => {
  isEdit.value = true
  form.value.relateWorkOrderCode = props.relateWorkOrderCode
}

const handleCancel = () => {
  showAddExist.value = false
  showAddNew.value = false
  isEdit.value = false
  fileList.value = []
  formRef.value?.resetFields()
  emit("refresh")
  emit("update:visible", false)
}
const formRef = ref()
const handleSave = async () => {
  //emit("save", form.value)

  await formRef.value.validate()
  // TODO: 调用保存接口
  let res = await $api.faultDealRelate(form.value)
  if (res && res.code === 0) {
    message.success("操作成功")
  }

  handleCancel()
}
const uploadUrl = async (val) => {
  return `${$api.uploadAction().url}`
}
const userInf = storage.getItem("USER_INFO")
const headers = ref({
  Authorization: "Bearer " + userInf.access_token,
})
const fileList = ref([])
const loading = ref(false)
const handleSubmit = async () => {
  // 处理发起新工单的逻辑

  await formRef.value.validate()
  loading.value = true
  form.value.attachFileIds = fileList.value
    .map((item) => item.response?.data?.id)
    .join(",")
  form.value.faultId = props.rowData?.id

  const { id, relateType, relateWorkOrderCode, ...other } = form.value
  let params = other
  let res = await $api.addWorkOrder(params)
  if (res && res.code === 0) {
    message.success("操作成功")
  }

  handleCancel()
}
//获取列表
const workListType = ref([])
const handleSearchWorkOder = async () => {
  const res = await $api.workOrderList({ current: 1, size: 9999 })
  workListType.value = res.data?.records
}
</script>

<style lang="less" scoped>
.content {
  text-align: center;
  padding: 20px;
  .tip {
    margin-bottom: 20px;
    color: #666;
  }
}
.btn-group {
  display: flex;
  justify-content: center;
  gap: 16px;
  padding: 20px 0;
}

.footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 24px;
}

.work-order-info {
  padding: 20px 0;
}

.upload-box {
  width: 100px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;

  &:hover {
    border-color: #1890ff;
  }

  .upload-btn {
    font-size: 24px;
    color: #999;
  }
}
.formInput,
.formSelect {
  width: 250px;
}
</style>
